package com.youmans.ossService.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.youmans.ossService.service.OssService;
import com.youmans.ossService.utils.UploadFile;
import com.youmans.servicebase.exceptionHandler.GuliException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    //单例
//    @Autowired
//    OSS ossClient ;




    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint ;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket ;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId ;

    @Value("${spring.cloud.alicloud.secret-key}")
    private String secretKey ;


//解决频繁更新图片shut down 错误
    @Bean
    public OSS ossClient() {
        return new OSSClientBuilder().build(endpoint, accessId, secretKey);
    }

    @Override
    public String uploadFileAvatar(MultipartFile multipartFile){
            if(!UploadFile.isPhoto(multipartFile)){
                //throw new GuliException(20001,"图片格式不对");
            }
            //阿里云存储图片
            String host = "https://" + bucket + "." + endpoint + "/"; // host的格式为 bucketname.endpoint
            String filename = multipartFile.getOriginalFilename();
            String fileSuffix = filename.substring(filename.lastIndexOf("."), filename.length());
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return null ;
        }
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            String dir = format + "/"; // 用户上传文件时指定的前缀。
            ossClient().putObject(bucket, dir + uuid + fileSuffix, inputStream);
            ossClient().shutdown();
            String urlImg = host + dir + uuid + fileSuffix;
            return urlImg;
    }
}
